﻿using System;
using System.Net.Http;

using Microsoft.AspNetCore.Http;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

using zijian666.WebApi.Default;

namespace zijian666.WebApi
{
    public partial class WebApiOptions
    {
        /// <summary>
        /// 添加可跟踪的 <seealso cref="HttpClient"/>
        /// <br>在使用可跟踪 <seealso cref="HttpClient"/> 发送请求时，会在请求头中写入X-Correlation-ID: <seealso cref="HttpContext.TraceIdentifier"/></br>
        /// </summary>
        /// <param name="name">客户端名称</param>
        public IHttpClientBuilder AddTraceableHttpClient(string name) => _services.AddHttpClient(name).Traceable();
    }

    public static partial class WebApiExtensions
    {

        /// <summary>
        /// <seealso cref="HttpClient"/> 增加可跟踪功能 
        /// <br>在发送请求时，会在请求头中写入X-Correlation-ID: <seealso cref="HttpContext.TraceIdentifier"/></br>
        /// </summary>
        /// <param name="builder">可用于配置客户端的 <seealso cref="IHttpClientBuilder"/>。</param>
        public static IHttpClientBuilder Traceable(this IHttpClientBuilder builder)
        {
            if (builder is null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            builder.Services.TryAddSingleton<TracingHttpMessageHandler>();
            return builder.AddHttpMessageHandler<TracingHttpMessageHandler>();
        }
    }
}
